#include "Light.h"
#include <iostream>
using namespace Nitro::Renderer;

Light::Light()
{
    float verts[] = {
        1.f,  0.f, 1.f,  //
        1.f,  0.f, -1.f, //
        -1.f, 0.f, -1.f, //
        -1.f, 0.f, 1.f,  //
    };
    BufferDescriptor bufferDesc;
    bufferDesc.bindFlags = BindFlags::VertexBuffer;
    bufferDesc.size = sizeof(verts);
    bufferDesc.appendAttribute(0, 3 * sizeof(float), Format::RGB32Float);
    vertexBuffer = CreateBuffer(bufferDesc, verts);

    ShaderDescriptor shaderDesc;
    shaderDesc.type = ShaderType::VertexShader;
    shaderDesc.sourceType = ShaderSourceType::SourceCode;
    shaderDesc.source = R"delimiter(
    #version 450 core
    in vec3 position;
    uniform mat4 modelMatrix;
    uniform mat4 viewProjectionMatrix;
    void main() {
        gl_Position = viewProjectionMatrix * modelMatrix * vec4(position, 1.0f);
    }
    )delimiter";
    auto vs = CreateShader(shaderDesc);
    if (vs.hasReport())
    {
        std::cout << vs.getReport() << '\n';
    }
    shaderDesc.type = ShaderType::FragmentShader;
    shaderDesc.sourceType = ShaderSourceType::SourceCode;
    shaderDesc.source = R"delimiter(
    #version 450 core
    uniform vec3 lightColor;
    out vec4 fragColor;
    void main() {
        fragColor = vec4(lightColor, 1.0f);
    }
    )delimiter";
    auto fs = CreateShader(shaderDesc);
    if (fs.hasReport())
    {
        std::cout << fs.getReport() << '\n';
    }

    PipelineDescriptor pipelineDesc;
    pipelineDesc.vertexShader = vs;
    pipelineDesc.fragmentShader = fs;
    pipelineDesc.drawMode = DrawMode::TriangleFan;
    pipeline = CreatePipeline(pipelineDesc);
}

void Light::render()
{
    updateMatrix();
    pipeline.setUniform("modelMatrix", modelMatrix);
    pipeline.setUniform("viewProjectionMatrix", Object3D::viewProjectionMatrix);
    pipeline.setUniform("lightColor", color);
    pipeline.activate();
    pipeline.setVertexBuffer(vertexBuffer);
    pipeline.draw(0, 4);
}